package com.cars.util.sign;

import java.util.Base64;

/**
 * @description:
 * @author: 孔垂云
 * @version: 1.0
 * @date: 2020/4/16 9:22
 */
public class Base64Util {
    public static final String Base64Charset = "utf-8";

    /**
     * 字符串转码
     *
     * @param str
     * @return
     */
    public static String encode(String str) {
        String base64encodedString = "";
        try {
            base64encodedString = Base64.getEncoder().encodeToString(str.getBytes(Base64Charset));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return base64encodedString;
    }

    /**
     * 字符串转码转成byte
     *
     * @param bytes
     * @return
     */
    public static String encode(byte[] bytes) {
        String base64encodedString = "";
        try {
            base64encodedString = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return base64encodedString;
    }

    /**
     * 字符串解码
     *
     * @param str
     * @return
     */
    public static String decode(String str) {
        String base64DecodeString = "";
        try {
            byte[] base64decodedBytes = Base64.getDecoder().decode(str);
            base64DecodeString = new String(base64decodedBytes, Base64Charset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return base64DecodeString;
    }

    /**
     * 字符串解码到byte
     *
     * @param str
     * @return
     */
    public static byte[] decodeToByte(String str) {
        try {
            byte[] base64decodedBytes = Base64.getDecoder().decode(str);
            return base64decodedBytes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(Base64Util.encode("中国"));
        System.out.println(Base64Util.decode("5Lit5Zu9"));
    }
}
